//
//  UIColor+HBCategory.m
//  HBLibary
//
//  Created by Rambo on 2018/10/26.
//

#import "UIColor+HBCategory.h"

@implementation UIColor (HBCategory)


/**
 16进制创建颜色，支持RGBA、RGB
 
 @param hex 16进制，支持 # 、0x 、0X 开头的16进制
 @return 颜色
 */
+ (UIColor*)hb_colorWithHexString:(NSString*)hex{
    
    
    NSString *hexString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    UIColor *color = [UIColor clearColor];
    
    if (hex == nil || ![hexString isKindOfClass:[NSString class]] || hexString.length < 7 || hexString.length > 10) {
        return color;
    }
    
    
    if ([hex hasPrefix:@"#"]) {
        hexString = [hexString substringFromIndex:1];
    }else if ([hexString hasPrefix:@"0X"]){
        hexString = [hexString substringFromIndex:2];
    }
    
    
    if (hexString.length == 6 || hexString.length == 8) {
        CGFloat R = 0 , G = 0 , B = 0 , A = 1;
        
        NSRange range = NSMakeRange(0, 2);
        
        NSString *rStr = [hexString substringWithRange:range];
        R = [self hb_hexStringToInt:rStr] / 255.0f;
        
        range.location += range.length;
        NSString *gStr = [hexString substringWithRange:range];
        G = [self hb_hexStringToInt:gStr] / 255.0f;
        
        range.location += range.length;
        NSString *bStr = [hexString substringWithRange:range];
        B = [self hb_hexStringToInt:bStr] / 255.0f;
        
        NSString *aStr = @"ff";
        if (hexString.length == 8) {
            range.location += range.length;
            aStr = [hexString substringWithRange:range];
        }
        A = [self hb_hexStringToInt:aStr] / 255.0f;
        
        color = [UIColor colorWithRed:R green:G blue:B alpha:A];
    }
    
    return color;
}


+ (int)hb_hexStringToInt:(NSString*)hex{
    uint32_t result = 0;
    sscanf([hex UTF8String], "%X", &result);
    return  result;
}


@end
